package com.example.encrypt.interceptor;

import com.example.encrypt.annotation.Decode;
import com.example.encrypt.annotation.Encrypt;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.util.*;

/**
 * @description: 测试拦截器
 * @author: wen
 * @createDate: 2020/3/3
 * @version: 1.0
 */
//@Component
public class TestInterceptor extends HandlerInterceptorAdapter {

    /**
     * 在DispatcherServlet之前执行
     * */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        HashMap<String, String[]> hashMap = new HashMap<>(request.getParameterMap());
        String[] s = hashMap.get("s");
        System.out.println(s.toString());



        if(handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod)handler;

            //判断后执行操作...
            MethodParameter[] parameters = h.getMethodParameters();
            for (MethodParameter parameter : parameters) {
                Annotation[] parameterAnnotations = parameter.getParameterAnnotations();
                for (Annotation parameterAnnotation : parameterAnnotations) {
                    if (parameterAnnotation instanceof Decode){
                        String name = parameter.getParameter().getName();
                        String parameterName = parameter.getParameterName();
                        String parameter1 = request.getParameter(name);
                        request.setAttribute(name,"1111111111");

                    }
                }
            }

        }
        return true;

//        System.out.println("************BaseInterceptor preHandle executed**********");
//        return true;
    }

    /**
     * 在controller执行之后的DispatcherServlet之后执行
     * */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
        System.out.println("************BaseInterceptor postHandle executed**********");
    }

    /**
     * 在页面渲染完成返回给客户端之前执行
     * */
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        System.out.println("************BaseInterceptor afterCompletion executed**********");
    }

}
